import { ecs } from 'db://app-game/libs/ecs/ECS';
import { InventoryModelComp } from './model/InventoryModelComp';

/** 背包实例 */
@ecs.register('Inventory')
export class Inventory extends ecs.Entity {
  // 数据层
  InventoryModel!: InventoryModelComp;
  init() {
    // 1.初始化背包
    this.addComponents(InventoryModelComp);
  }

  /**
   * 添加物品
   * @param id 物品ID
   * @param count 数量
   * @returns 剩余数量
   */
  addItem(id: number, count: number): { id: number; count: number } {
    this.InventoryModel.tableItem.init(id);
    const data = this.InventoryModel.tableItem.data;
    if (!this.InventoryModel.items.has(id)) {
      const params = {
        id,
        ...data,
        count: 0,
      };
      this.InventoryModel.items.set(id, params);
    }
    const item = this.InventoryModel.items.get(id);
    if (data.maxCount < item.count + count) {
      let remainCount = item.count + count - data.maxCount;
      item.count = data.maxCount;
      return { id, count: remainCount };
    } else {
      item.count += count;
      return { id, count: 0 };
    }
  }

  /**
   * 批量添加物品
   * @param res 物品列表
   */
  batchAddItem(res: { id: number; count: number }[]): { id: number; count: number }[] {
    const remainCount: { id: number; count: number }[] = [];
    for (let i = 0; i < res.length; i++) {
      let { id, count } = res[i];
      const result = this.addItem(id, count);
      if (result.count > 0) {
        remainCount.push({ id, count: result.count });
      }
    }
    return remainCount;
  }

  /**
   * 移除物品
   * @param id 物品ID
   * @param count 数量
   * @returns 剩余数量
   */
  removeItem(id: number, count: number): { id: number; count: number } {
    if (!this.InventoryModel.items.has(id)) {
      return { id, count: 0 };
    }
    const item = this.InventoryModel.items.get(id);
    if (item.count < count) {
      return { id, count: item.count };
    }
  }
}
